package com.prothink.threadadmindemo.controller;

public class DingYIRanController {
    private int number = 0;
    private final Object lock = new Object();

    public static void main(String[] args) {
        DingYIRanController printOddEven = new DingYIRanController();
        Thread oddThread = new Thread(printOddEven.new OddRunnable());
        Thread evenThread = new Thread(printOddEven.new EvenRunnable());
        oddThread.start();
        evenThread.start();
    }

    class OddRunnable implements Runnable {
        @Override
        public void run() {
            while (number <= 100) {
                synchronized (lock) {
                    if (number % 2 == 0) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println("Odd: " + number++);
                        lock.notify();
                    }
                }
            }
        }
    }

    class EvenRunnable implements Runnable {
        @Override
        public void run() {
            while (number <= 100) {
                synchronized (lock) {
                    if (number % 2 != 0) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println("Even: " + number++);
                        lock.notify();
                    }
                }
            }
        }
    }
}
